#ifndef THREAD_WORK_H
#define THREAD_WORK_H

#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>


#include "getHtml.h"
#include "common.h"

 queue<UrlPath*>  m_qUrlPath;
boost::mutex io_mutex;


boost::condition_variable cond;

 typedef boost::mutex::scoped_lock
        scoped_lock;
        
class printer
{
public:
    printer(boost::asio::io_service& io)
        : strand_(io),
        timer1_(io, boost::posix_time::seconds(1)),
   //     timer2_(io, boost::posix_time::seconds(1)),
        count_(0)
    {
        timer1_.async_wait(strand_.wrap(boost::bind(&printer::dequeue, this)));
        //timer2_.async_wait(strand_.wrap(boost::bind(&printer::writeFIFO, this)));
    }

    ~printer()
    {
        std::cout << "Final count is " << count_ << "\n";
    }

    void dequeue()
    {
         scoped_lock lock(io_mutex);
        
                     //    boost::mutex::scoped_lock                        lock(io_mutex);
                      
                             //   lock(mut);
                                
        while(m_qUrlPath.empty())
        {
            cond.wait(lock);        
        
        }
        {
        if (!m_qUrlPath.empty())
        {
          //  dhw_UrlPath::instance()->size();
           // UrlPath  * url =  dhw_UrlPath::instance()->front();
          //  dhw_UrlPath::instance()->pop();
            UrlPath  * url =  m_qUrlPath.front();
            m_qUrlPath.pop();
            getHtml * gh = new getHtml;
            gh->setUrl(url);
            gh->doWork();
            delete gh;
        }
   cond.notify_one();
        }
        timer1_.expires_at(timer1_.expires_at() + boost::posix_time::seconds(1));
        timer1_.async_wait(strand_.wrap(boost::bind(&printer::dequeue, this)));        
    }

    //void writeFIFO()
    //{
    //
    //  std::cout << "-----------------Timer 2: " << count_ << "\n";
    //    if (count_ < 10)
    //    {
    //        std::cout << "Timer 2: " << count_ << "\n";
    //        ++count_;

    //        timer2_.expires_at(timer2_.expires_at() + boost::posix_time::seconds(1));
    //        timer2_.async_wait(strand_.wrap(boost::bind(&printer::writeFIFO, this)));
    //    }
    //}

private:
    boost::asio::strand strand_;
    boost::asio::deadline_timer timer1_;
   // boost::asio::deadline_timer timer2_;
    int count_;
};


#endif